package net.topicopedia.other;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.FilterOperator;

@SuppressWarnings("serial")
public class GetUserTopicsServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		resp.addHeader("Access-Control-Allow-Origin", "*");
		resp.setContentType("text/plain");
		
		String output = "";
		
		String userStirng = req.getParameter("user");
		Key userKey = KeyFactory.createKey("User", (Long) Long.parseLong(userStirng) );
		
		String tags = (String) req.getParameter("tags");
		List<String> searchTags = Arrays.asList(tags.split(", "));
		
		if ( searchTags.isEmpty() )
		{
			output = "[]";
			resp.getWriter().println( output );
			return;
		}
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		Query query = new Query("UserTopic").setFilter( new FilterPredicate("user", FilterOperator.EQUAL, userKey) );
		PreparedQuery pq = datastore.prepare(query);
		
		List<Key> topicsToGet = new ArrayList<Key>();
		
		for (Entity userTopic : pq.asIterable() ) {
			
			if ( userTopic != null )
			{
				Key topicKey = (Key) userTopic.getProperty("topic");
				
				if ( topicKey != null )
				{
					
					Entity topic = null;
					try {
						topic = datastore.get( topicKey );
						
						Boolean addTopic = false;
						
						@SuppressWarnings("unchecked")
						List<String> topicTags = (List<String>) topic.getProperty("tags");
						
						Iterator<String> searchTagsIterator = searchTags.iterator();
						while( searchTagsIterator.hasNext() ) 
						{
							if ( !addTopic )
							{
								String searchTag = searchTagsIterator.next();
								if ( topicTags.contains( searchTag ) )
						        {
						        	 addTopic = true;
						        	 topicsToGet.add( userTopic.getKey() );
						        }
							} 
					    }
						
					} catch (EntityNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
		}
		
		Map<Key, Entity> topics = datastore.get(topicsToGet); 
		
		output = "[";
		
		Iterator<Key> keySetIterator = topics.keySet().iterator();
		
		while  ( keySetIterator.hasNext() )
		{
			Key topicKey = keySetIterator.next();
			Entity userTopic = topics.get(topicKey);
			
			if ( userTopic != null )
			{
				String storedUuid = userTopic.getKey().getId() + "";
				String userUuid = ( (Key) userTopic.getProperty("user") ).getId() + "";
				String topicUuid = ( (Key) userTopic.getProperty("topic") ).getId() + "";
				String items = ( ( Text) userTopic.getProperty("items") ).getValue();
				String references = ( ( Text) userTopic.getProperty("references") ).getValue();
				
				if ( output.length() > 1 )
				{
					output += ", ";
				}
				
				output += "{\"uuid\": " + storedUuid;
				output += ", \"user\": " + userUuid;
				output += ", \"topic\": " + topicUuid;
				if ( items.length() > 0 )
				{
					output += ", \"items\": " + items;
				}
				if ( references.length() > 0 )
				{
					output += ", \"references\": " + references;
				}
				output += "}";
				
			}
			output += "]";
		}
		
		
		resp.getWriter().println( output );
		
	}
}
 